package com.mission.schedule.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.mission.schedule.R;
import com.mission.schedule.adapter.QDLongImageSaveAdapter;
import com.mission.schedule.adapter.QDLongImageSaveAdapter1;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.utils.AfterPermissionGranted;
import com.mission.schedule.utils.EasyPermissions;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

@SuppressLint({"SimpleDateFormat", "HandlerLeak"})
public class QDLongImageSaveActivity1 extends BaseActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {

    @ViewResId(id = R.id.recylerview)
    private RecyclerView recylerview;
    @ViewResId(id = R.id.back)
    private Button back;
    @ViewResId(id = R.id.save)
    private Button save;


    Context context;

    String time, userid, ringdesc, ringcode;
    String addcopy = "1";
    String addicon = "0";

    SharedPrefUtil sharedPrefUtil = null;

    QDLongImageSaveAdapter1 qdLongImageSaveAdapter;

    List<QDFXDetailActivity.QDBean.ListBean> list = new ArrayList<>();

    int stylee = 0;

    @Override
    protected void setListener() {
        back.setOnClickListener(this);
        save.setOnClickListener(this);
    }

    int maxTitleId = 1;
    String title = "";
    String name = "";

    @Override
    protected void setContentView() {
        setContentView(R.layout.longimgesave_qdlist);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;

        list = (List<QDFXDetailActivity.QDBean.ListBean>) getIntent().getSerializableExtra("list");

        stylee = getIntent().getIntExtra("stylee", 0);
        title = getIntent().getStringExtra("title");
        name = getIntent().getStringExtra("name");
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        userid = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERID, "");
        time = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.ALLTIME, "08:58");


        loadData();
    }


    private void loadData() {

    }


    @Override
    protected void setAdapter() {
        qdLongImageSaveAdapter = new QDLongImageSaveAdapter1(context, list, maxTitleId,
                Integer.valueOf(userid), Integer.valueOf(addicon), addcopy, stylee, title, name);
        recylerview.setLayoutManager(new LinearLayoutManager(this));
        recylerview.setItemAnimator(new DefaultItemAnimator());
        recylerview.setAdapter(qdLongImageSaveAdapter);
    }

    ProgressUtil progressUtil = new ProgressUtil();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.back:
                onBackPressed();
                break;
            case R.id.save:
                checkPhonePermission();
                if (autoFag) {
                    progressUtil.ShowProgress(context, true, true, "生成长图中..");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            savePic(shotRecyclerView(recylerview), true);
                        }
                    }, 500);
                } else {
                    Toast.makeText(context, "请设置时间表存储权限!", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }


    /**
     * 保存到sdcard
     *
     * @param b
     * @return
     */
    public String savePic(Bitmap b, boolean issave) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
                Locale.US);

        String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
        File outfile = new File(dicr, "TimeApp");
        // 如果文件不存在，则创建一个新文件
        if (!outfile.isDirectory()) {
            try {
                outfile.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        final String name = sdf.format(new Date()) + ".png";
        final String fname = outfile + "/" + name;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fname);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 50, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (issave) {
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        fname, name, null);
                //发广播告诉相册有图片需要更新，这样可以在图册下看到保存的图片了
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(new File(fname));
                intent.setData(uri);
                sendBroadcast(intent);
                progressUtil.dismiss();
                Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
                onBackPressed();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
            }

        } else {
            progressUtil.dismiss();
            Toast.makeText(context, "长图生成完成", Toast.LENGTH_SHORT).show();
//            showShareLongImage(fname);
            finish();
        }

        return fname;
    }


    public static Bitmap shotRecyclerView(RecyclerView view) {
        RecyclerView.Adapter adapter = view.getAdapter();
        Bitmap bigBitmap = null;
        if (adapter != null) {
            int size = adapter.getItemCount();
            int height = 0;
            Paint paint = new Paint();
            int iHeight = 0;
            final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

            // Use 1/8th of the available memory for this memory cache.
            final int cacheSize = maxMemory / 8;
            LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
            for (int i = 0; i < size; i++) {
                RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
                adapter.onBindViewHolder(holder, i);
                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                Bitmap drawingCache = holder.itemView.getDrawingCache();
                if (drawingCache != null) {

                    bitmaCache.put(String.valueOf(i), drawingCache);
                }
                height += holder.itemView.getMeasuredHeight();
            }
            bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_4444);
            Canvas bigCanvas = new Canvas(bigBitmap);
            Drawable lBackground = view.getBackground();
            if (lBackground instanceof ColorDrawable) {
                ColorDrawable lColorDrawable = (ColorDrawable) lBackground;
                int lColor = lColorDrawable.getColor();
                bigCanvas.drawColor(lColor);
            }

            for (int i = 0; i < size; i++) {
                Bitmap bitmap = bitmaCache.get(String.valueOf(i));
                bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
                iHeight += bitmap.getHeight();
//                bitmap.recycle();
            }
        }
        return bigBitmap;
    }

    public static Bitmap shotView(View view) {
        Bitmap bigBitmap = null;
        int height = 0;
        Paint paint = new Paint();
        int iHeight = 0;
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 8;
        LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
        Bitmap drawingCache = view.getDrawingCache();
        if (drawingCache != null) {
            bitmaCache.put("1", drawingCache);
        }

        bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas bigCanvas = new Canvas(bigBitmap);
        Drawable lBackground = view.getBackground();
        if (lBackground instanceof ColorDrawable) {
            ColorDrawable lColorDrawable = (ColorDrawable) lBackground;
            int lColor = lColorDrawable.getColor();
            bigCanvas.drawColor(lColor);
        }

        for (int i = 0; i < 1; i++) {
            Bitmap bitmap = bitmaCache.get(String.valueOf(i));
            bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
            iHeight += bitmap.getHeight();
//                bitmap.recycle();
        }
        return bigBitmap;
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }


    static boolean autoFag = false;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;

    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    private void checkPhonePermission() {
        if (Build.VERSION.SDK_INT < 23) {
            autoFag = true;
        } else {
            String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(QDLongImageSaveActivity1.this, perms)) {
                // Have permissions, do the thing!
                autoFag = true;
            } else {
                // Ask for both permissions
                EasyPermissions.requestPermissions(this, "该功能需要此权限，为了保证应用正常运行!",
                        RC_LOCATION_CONTACTS_PERM, perms);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
            autoFag = true;
        } else {
            autoFag = false;
        }
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d("TAG", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
// (Optional) Check whether the user denied permissions and checked NEVER ASK AGAIN.
        // This will display a dialog directing them to enable the permission in app settings.
        EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
                getString(R.string.rationale_ask_again),
                R.string.action_settings, R.string.cancel, null, perms);
    }


    /**
     * 分享长图
     *
     * @param imagepath
     */
    private void showShareLongImage(String imagepath) {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath(imagepath);//
        // 确保SDcard下面存在此张图片
        oks.show(this);

        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Toast.makeText(context, "1", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Toast.makeText(context, "2", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Toast.makeText(context, "3", Toast.LENGTH_SHORT).show();
            }
        });


    }

}
